package com.denghq.projectbuilder.component.remote.utils;


import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class BeanTool {

    private static ObjectMapper MAPPER = new ObjectMapper();
    static {
       /* DateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
        TimeZone zone = TimeZone.getTimeZone("GMT+8");
        sf.setTimeZone(zone);
        MAPPER.setDateFormat(sf);*/
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public static <T> T mapToObject(Map<String, Object> map, Class<T> beanClass){
        if (map == null)
            return null;
        try {
            return  MAPPER.readValue(MAPPER.writeValueAsString(map), beanClass);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("{}数据转换错误:{}",map,e.getMessage());
            return null;
        }
    }

    public static Map<?, ?> objectToMap(Object obj) {
        if(obj == null)
            return null;
        try {
            return MAPPER.readValue(objectToJsonStr(obj), HashMap.class);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("{}数据转换错误:{}", obj,e.getMessage());
            return null;
        }
    }

    public static String objectToJsonStr(Object obj) {
        if(obj == null)
            return null;
        try {
            return MAPPER.writeValueAsString(obj);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("{}数据转换错误:{}", obj,e.getMessage());
            return null;
        }
    }
}
